

class ScrollList{
    constructor(){

    }

    /**
     * 渲染虚拟节点，返回节点数组
     * @param {*} listData 
     * @param {*} callback 
     */
    renderToString(listData, callback) {

        const listDoc = document.getElementsByClassName("scroll-list")
        const listBox = document.getElementsByClassName("scroll-list-ul")
        const doc = listDoc && listDoc[0]
        const box = listBox && listBox[0]
        const docHeight = "600px"
        const boxHeight = (listData.length * 21) + "px"
        const liHeight = 21

        doc.style.height = docHeight
        box.style.height = boxHeight


        // 首次渲染
        let startIndex = 0
        let showLength = parseInt(parseInt(docHeight)/liHeight) + 10
        listData = this.initList(listData, liHeight)
        const content = this.renderList(listData, startIndex, startIndex+showLength)
        callback(content)



        const onScrollAtTime = this.throttle(this.onScroll, 10)

        doc.addEventListener("scroll", onScrollAtTime)
    }

    /**
     * 初始化list中node的top值
     * @param {*} list 
     * @param {*} liHeight 
     * @returns 
     */
    initList (list, liHeight) {
        const nodes = list.map((item, index) => {
            item._top = (liHeight * index) + "px"

            return item
        })

        return nodes
    }

    onScroll (e) {
        console.log("e:", e.target)

        const scrollTop = e.target.scrollTop 
        let currentIndex = parseInt(scrollTop/liHeight)

        if(currentIndex !== startIndex){
            // 向前冗余10条数据，向后冗余10条数据
            let start = currentIndex
            let end = currentIndex + showLength + 10
            if(currentIndex > 10){
                start = currentIndex - 10
            }
            const nodes = this.renderList(listData, start, end)
            callback && callback(nodes)

            startIndex = currentIndex
        }
    }

    /**
     * 重新渲染数据
     * @param {*} listData 
     * @param {*} start 
     * @param {*} end 
     * @returns 
     */
    renderList (listData, start=0, end=start+10) {
        const nodes = listData.slice(start, end).map((item, index) => {
            let liNode = document.createElement("li")
            liNode.style.position = "absolute"
            liNode.style.top = item._top
            liNode.innerHTML = `${item.id}，${item.name}：${item.age}`

            return liNode
        })

        return nodes
    }

    /**
     * 防抖函数
     * @param {*} fn 
     * @param {*} wait 
     * @returns 返回一个新的 function
     */
    throttle (fn, wait=100) {

        if(Object.prototype.toString.call(fn)!=="[object Function]"){
            throw Error("必须传递一个函数作为参数！")
            return
        }

        let timer = null

        return function(){
            clearTimeout(timer)
            timer = setTimeout(()=>{
                fn.call(this, ...arguments)
            }, wait)
        }
    }
}





export default renderToString